# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA


from turbogears import controllers, expose, flash, url, config, i18n
# from model import *
import pkg_resources
import os, datetime
try:
    pkg_resources.require("SQLAlchemy>=0.4.3")
except pkg_resources.DistributionNotFound:
    import sys
    print >> sys.stderr, """You are required to install SQLAlchemy but appear not to have done so.
Please run your projects setup.py or run `easy_install SQLAlchemy`.

"""
    sys.exit(1)
from turbogears import identity, redirect
from cherrypy import request, response
# from tginvoice import json

from tginvoice.model import tables, database
from tginvoice.utils import standard

import logging
log = logging.getLogger("tginvoice.controllers")

from turbogears import validators
#, controllers, expose, validate, error_handler
from toscawidgets.widgets.forms import *
from datetime import datetime
from plotkit import EasyPlot

class ControllerObj(controllers.Controller):

    def check_identity_user(self, obj):
        if identity.not_anonymous():
            if identity.current.user.user_id == obj.user.user_id:
                return True
        return False

    def __init__(self,  parent=None, name='/', *args, **kw):
        controllers.Controller.__init__(self)
        #self._loader = loader
        self._parent = parent
        self._name = name
        self._map = {}
        self._childs = []
        for key, value in kw.iteritems():
            setattr(self, key, value)
        self._set_childs()

    def _get_parent(self):
        return self._parent

    parent = property(_get_parent)

    def _get_has_parent(self):
        if self.parent:
            return True
        else:
            return False

    has_parent = property(_get_has_parent)

    def _get_name(self):
        return self._name

    name = property(_get_name)

    def _get_map(self):
        return self._map

    map = property(_get_map)

    def _get_has_map(self):
        if self.map:
            return True
        else:
            return False

    has_map = property(_get_has_map)

    def _set_child(self, name):
        pass

    def _set_childs(self):
        pass

    def _get_childs(self):
        return self._childs

    childs = property(_get_childs)

    def _get_has_childs(self):
        if self.childs:
            return True
        else:
            return False

    has_childs = property(_get_has_childs)


    # USER
    def _get_id(self):
        if identity.not_anonymous():
            return identity.current.user.user_id
        else:
            return None

    id = property(_get_id)

    def _get_user(self):
        if identity.not_anonymous():
            return identity.current.user
        else:
            return None

    puser = property(_get_user)

    #BILLER
    def _get_biller(self):
        if len(identity.current.user.biller) == 1:
            return identity.current.user.biller[0]

    pbiller = property(_get_biller)

    def _get_iterator_biller(self):
        return standard.BILLER_LST

    iterator_biller = property(_get_iterator_biller)

    def _get_mapper_biller(self):
        return standard.BILLER_MAP

    mapper_biller = property(_get_mapper_biller)

    # CUSTOMERS
    def _get_customers(self):
        if len(identity.current.user.customer) == 1:
            return identity.current.user.customer

    pcustomers = property(_get_customers)

    def _get_customer(self, id):
        return database.get_customer(id)

    def _get_iterator_customer(self):
        return standard.CUSTOMER_LST

    iterator_customer = property(_get_iterator_customer)

    def _get_iterator_customer_editable(self):
        return standard.CUSTOMER_EDITABLE

    iterator_customer_editable = property(_get_iterator_customer_editable)

    def _get_mapper_customer(self):
        return standard.CUSTOMER_MAP

    mapper_customer = property(_get_mapper_customer)

    def _get_product(self, id):
        return database.get_product(id)

    # INVOICE
    def _get_invoices(self):

        if self.pbiller:
            return self.pbiller.invoice_biller

    pinvoices = property(_get_invoices)

    def _get_proformas(self):
        return database.get_proformas(self.id)

    pproformas = property(_get_proformas)

    def _get_invoice(self, id, var='invoice'):
        if var == 'invoice':
            return database.get_invoice(id)
        elif var == 'proforma':
            return database.get_proforma(id)

    def _get_iterator_invoice(self):
        return standard.INVOICE_LST

    iterator_invoice = property(_get_iterator_invoice)

    def _get_mapper_invoice(self):
        return standard.INVOICE_MAP

    mapper_invoice = property(_get_mapper_invoice)

    def _get_iterator_product(self):
        return standard.PRODUCT_LST

    iterator_product = property(_get_iterator_product)

    def _get_iterator_product_form(self):
        return standard.PRODUCT_FORM

    iterator_product_form = property(_get_iterator_product_form)

    def _get_mapper_product(self):
        return standard.PRODUCT_MAP

    mapper_product = property(_get_mapper_product)

    # PROJECT - TASK
    def _get_projects(self):
        return database.get_projects(self.id)

    pprojects = property(_get_projects)

    def _get_project(self, id):
        return database.get_project(id)

    def _get_iterator_project(self):
        return standard.PROJECT_LST

    iterator_project = property(_get_iterator_project)

    def _get_iterator_project_form(self):
        return standard.PROJECT_FORM

    iterator_project_form = property(_get_iterator_project_form)

    def _get_milestone(self, id):
        return database.get_milestone(id)

    def _get_mapper_project(self):
        return standard.PROJECT_MAP

    mapper_project = property(_get_mapper_project)

    def _get_iterator_milestone(self):
        return standard.MILESTONE_LST

    iterator_milestone = property(_get_iterator_milestone)

    def _get_iterator_milestone_form(self):
        return standard.MILESTONE_FORM

    iterator_milestone_form = property(_get_iterator_milestone_form)

    def _get_mapper_milestone(self):
        return standard.MILESTONE_MAP

    mapper_milestone = property(_get_mapper_milestone)

    def _get_iterator_task(self):
        return standard.TASK_LST

    iterator_task = property(_get_iterator_task)

    def _get_iterator_task_form(self):
        return standard.TASK_FORM

    iterator_task_form = property(_get_iterator_task_form)

    def _get_mapper_task(self):
        return standard.TASK_MAP

    mapper_task = property(_get_mapper_task)

    def _get_iterator_tab(self):
        return standard.TAB_LIST

    iterator_tab = property(_get_iterator_tab)

    def _get_iterator_currency(self):
        return standard.CURRENCY_LST

    iterator_currency = property(_get_iterator_currency)

    def _get_biller_logo(self):
        if self.id:
            return  os.path.join(
                 config.get('static_filter.dir',path='/static'),
                 'rml/%s/logo.png'%identity.current.user.user_name)

    biller_logo = property(_get_biller_logo)

    def invoice_rml(self, i18n=''):
        if self.id:
            ret = os.path.join(
                 config.get('static_filter.dir',path='/static'),
                 'rml/%s/invoice-%s.html'%(identity.current.user.user_name,
                                           i18n))
            if os.path.exists(ret):
                return ret
            return os.path.join(
                 config.get('static_filter.dir',path='/static'),
                 'rml/invoice.html')

    def _get_invoice_tmpl(self):
        path = os.path.join(config.get('static_filter.dir',path='/static'),'rml/%s'%(
                                            identity.current.user.user_name))
        ret = []
        if os.path.exists(path):
            for name in os.listdir(path):
                if name.startswith('invoice-'):
                    i18n = name.replace('invoice-','')
                    i18n = i18n.replace('.html', '')
                    ret.append(i18n)
        return ret

    invoice_tmpl = property(_get_invoice_tmpl)

    def _get_output_path(self):
        if self.id:
            ret = os.path.join(
                 config.get('static_filter.dir',path='/static'),
                 'output/%s'%identity.current.user.user_id)
            if not os.path.exists(ret):
                os.makedirs(ret)
            return ret

    output_path = property(_get_output_path)


    def _get_date_now(self):
        import datetime
        t = datetime.date.today()
        year =  t.strftime("%Y")
        month = t.strftime("%m")
        day = t.strftime("%d")
        return year, month,day

    date = property(_get_date_now)

    def _get_release(self):
        import tginvoice.release
        return tginvoice.release

    release = property(_get_release)

    def _get_mapper_general(self):
        return standard.GENERAL_MAP

    mapper_general = property(_get_mapper_general)

    def _get_mapper_error(self):
        return standard.ERROR_MAP

    mapper_error = property(_get_mapper_error)

    def _get_mapper_tab(self):
        return standard.TAB_MAP

    mapper_tab = property(_get_mapper_tab)

    def _get_mapper_action(self):
        return standard.ACTION_MAP

    mapper_action = property(_get_mapper_action)

    def _get_locale(self):
        return i18n.get_locale()

    locale = property(_get_locale)

    def _get_date_format(self):
        return i18n.format.get_date_format('short')

    date_format = property(_get_date_format)

    def date_i18n(self, convert):
        return convert.strftime(self.date_format)


    def date_validate(self, convert):
        if hasattr(datetime, 'strptime'):
            d = datetime.strptime(convert, self.date_format)

        else:
            import time
            t1tmp = time.strptime(convert, self.date_format)
            d = datetime(*t1tmp[0:6])
        return d.strftime('%m/%d/%Y')

    def calendar(self, id=None, *args, **kw):
        return  CalendarDatePicker(id=id,
                                       calendar_lang=self.locale[:2],
                                       date_format=self.date_format,
                                       *args, **kw)
    def _get_tasks(self, project):
        milestones = project.milestones
        data = {}
        for milestone in milestones:
            if not data.has_key(milestone.name):
                data[milestone.name] = {}
            for task in milestone.tasks:
                if task.active:
                    if not data[milestone.name].has_key(task.priority):
                        data[milestone.name][task.priority] = 0
                data[milestone.name][task.priority] += 1
        return data

    def _get_tasks_plot(self, data):
        return self._get_pie_plot(data, "easyplot")

    def _get_tasks_active(self, project):
        milestones = project.milestones
        data = {}
        for milestone in milestones:
            if not data.has_key(milestone.name):
                data[milestone.name] = {}
                for val in ['active', 'closed']:
                    data[milestone.name][val]=0
            for task in milestone.tasks:
                if task.active:
                    data[milestone.name]['active'] += 1
                else:
                    data[milestone.name]['closed'] += 1
        return data

    def _get_tasks_active_plot(self, data):
        return self._get_pie_plot(data, "easyplot_active")

    def _get_pie_plot(self,data, css_id):
        ret = {}
        for key, value in data.iteritems():
            xticks = []
            data = []
            data_keys = value.keys()

            for index in range(len(data_keys)):
                xticks.append({'label': str(data_keys[index]), 'v': index})
                data.append([index, value[data_keys[index]]])

            ret[key] = EasyPlot(id='%s-%s'%(css_id, key),
                                style="pie",
                                data=[data],
                                width=200,
                                height=200,
                                option={'xTicks': xticks,
                                        'pieRadius': 0.4,
                                        'drawBackground': 0,
                                        'padding': {'left': 10, 'right':10, 'top': 10, 'bottom': 10},
                                        })

        return ret
